<template>
	<view class="container">
		<view class="header">
			<view class="title">我的报价记录</view>
			<view class="subtitle">您提交的所有报价</view>
		</view>

		<view class="search-box">
			<input class="search-input" type="text" v-model="query" placeholder="按采购单名称搜索..." @confirm="search" />
			<button class="search-btn" @click="search">搜索</button>
		</view>

		<unicloud-db ref="udb" v-slot:default="{data, pagination, loading, hasMore, error}" :collection="collectionList"
			:field="field" :where="where" :page-size="15" orderby="timestamp desc">
			<view v-if="error" class="error">{{error.message}}</view>
			<view v-else-if="data">
				<view class="list-container">
					<view class="list-item" v-for="(item, index) in data" :key="index" @click="goToAuctionDetail(item.auction_id[0]._id)">
						<view class="item-header">
							<text class="item-title">{{ item.auction_id[0] && item.auction_id[0].title }}</text>
							<text class="item-status" :class="item.auction_id[0] && item.auction_id[0].status">{{ auctionStatusText(item.auction_id[0] && item.auction_id[0].status) }}</text>
						</view>
						<view class="item-content">
							<text class="item-number">采购单编号: {{ item.auction_id[0] && item.auction_id[0].serial_number }}</text>
							<text class="item-price">我的报价: ¥{{ item.amount }}</text>
							<text class="item-time">报价时间: {{ formatDate(item.timestamp) }}</text>
						</view>
					</view>
				</view>
			</view>
			<uni-load-more v-if="data && data.length > 0" :status="loading ? 'loading' : (hasMore ? 'more' : 'noMore')"></uni-load-more>
			<view v-if="data && data.length === 0 && !loading" class="no-data">
				<text>暂无报价记录</text>
			</view>
		</unicloud-db>
	</view>
</template>

<script>
	const db = uniCloud.database();

	export default {
		data() {
			return {
				collectionList: "bids,auctions",
				field: "amount,timestamp,auction_id{title,serial_number,status}",
				query: '',
				where: 'supplier_user_id == "invalid-user-id"', // 默认查询一个不存在的ID
				userId: null
			}
		},
		onShow() {
			const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {};
			const newUserId = userInfo._id || null;

			// 如果用户ID发生变化（切换了账户或首次加载），则重新加载数据
			if (this.userId !== newUserId) {
				this.userId = newUserId;
				if (this.userId) {
					this.where = `supplier_user_id == "${this.userId}"`;
					this.$nextTick(() => {
						if (this.$refs.udb) {
							this.$refs.udb.loadData({
								clear: true
							});
						}
					});
				} else {
					// 处理用户登出
					this.where = 'supplier_user_id == "invalid-user-id"';
					if (this.$refs.udb) {
						this.$refs.udb.clear();
					}
				}
			}
		},
		onPullDownRefresh() {
			if (this.userId && this.$refs.udb) {
				this.$refs.udb.loadData({
					clear: true
				}, () => {
					uni.stopPullDownRefresh()
				})
			} else {
				uni.stopPullDownRefresh()
			}
		},
		methods: {
			search() {
				const query = this.query.trim();
				let where = `supplier_user_id == "${this.userId}"`;
				if (query) {
					where += ` && auction_id.title.indexOf('${query}') > -1`;
				}
				this.where = where;
				this.$nextTick(() => {
					this.$refs.udb.loadData({
						clear: true
					});
				});
			},
			formatDate(timestamp) {
				if (!timestamp) return ''
				const date = new Date(timestamp)
				return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
			},
			auctionStatusText(status) {
				const statusMap = {
					'bidding': '竞价中',
					'finished': '已结束'
				}
				return statusMap[status] || status
			},
			goToAuctionDetail(auctionId) {
				if (!auctionId) return;
				uni.navigateTo({
					url: `/pages/auctions/detail?id=${auctionId}`
				})
			}
		}
	}
</script>

<style scoped>
	.container {
		padding: 20rpx;
	}
	
	.header {
		margin-bottom: 30rpx;
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	
	.subtitle {
		font-size: 28rpx;
		color: #999;
		margin-top: 10rpx;
	}
	
	.search-box {
		display: flex;
		margin-bottom: 30rpx;
	}
	
	.search-input {
		flex: 1;
		padding: 20rpx;
		border: 1rpx solid #e0e0e0;
		border-radius: 10rpx;
	}
	
	.search-btn {
		margin-left: 20rpx;
		padding: 20rpx;
		background-color: #007AFF;
		color: white;
		border-radius: 10rpx;
	}
	
	.list-container {
		background-color: white;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}
	
	.list-item {
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	.list-item:last-child {
		border-bottom: none;
	}
	
	.item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}
	
	.item-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		flex: 1;
	}
	
	.item-status {
		font-size: 24rpx;
		padding: 5rpx 15rpx;
		border-radius: 5rpx;
	}
	
	.item-status.bidding {
		background-color: #e6fffb;
		color: #007AFF;
	}
	
	.item-status.finished {
		background-color: #f0f0f0;
		color: #999;
	}
	
	.item-content {
		display: flex;
		flex-direction: column;
	}
	
	.item-content text {
		font-size: 26rpx;
		color: #666;
		margin-bottom: 10rpx;
	}
	
	.item-content text:last-child {
		margin-bottom: 0;
	}
	
	.no-data {
		text-align: center;
		padding: 100rpx;
		color: #999;
	}
</style>